package com.lagou.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断是否是登录的 url,如果是则放行
        String uri = request.getRequestURI();
        if(uri.indexOf("/login")!=-1){
            return true;
        } else {
            //判断 session 中是否存了 username
            String username = (String) request.getSession().getAttribute("username");
            if(username!=""&&username!=null){
                return true;
            }else{
                //重定向到 login 页面
                request.getRequestDispatcher("login").forward(request, response);
                return false;
            }
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle");

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion");
    }
}
